<template>
  <div class="add-user">
    <el-dialog :title="title" :visible.sync="visible" width="600px" @close="formCancel()">
      <el-form v-if="visible" ref="editForm" :model="formData" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" type="text" placeholder="请输入角色名称" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="唯一编码" prop="code">
          <el-input v-model="formData.code" type="text" placeholder="请输入编码" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="formData.sort" type="number" placeholder="请输入排序" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入备注" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item style="margin-top:20px;width: 100%;display: flex;justify-content: center;">
          <el-button style="margin-right:20px;" @click="formCancel">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { setRole } from '@/api/system'
export default {
  name: 'EditRole',
  components: {},
  props: {},
  data() {
    return {
      title: '角色编辑',
      formData: {
        sort: 100
      },
      visible: false,
      rules: {
        name: [
          {
            required: true, message: '角色名称不能为空', trigger: 'blur'
          }
        ],
        code: [
          {
            required: true, message: '编码不能为空', trigger: 'blur'
          }
        ]
      }
    }
  },
  destroyed() {
  },
  methods: {
    add() {
      this.visible = true
      this.formData = {
        sort: 100
      }
      this.title = '新增角色'
    },
    edit(records) {
      this.visible = true
      this.title = '编辑角色'
      this.formData = {
        code: records.code,
        id: records.id,
        name: records.name,
        remark: records.remark,
        sort: records.sort
      }
    },
    formCancel() {
      this.visible = false
    },
    async submit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          setRole(this.formData).then(res => {
            if (res.success) {
              this.$message({
                message: this.title.substring(0, 2) + '成功',
                type: 'success'
              })
              this.$emit('reload')
              this.visible = false
            }
          })
        } else {
          return false;
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
